import tkinter as tk
import threading

# 创建主窗口
root = tk.Tk()
root.title("AI易经出行")
root.geometry("800x600")

# 添加关闭确认功能
def on_closing():
    import tkinter.messagebox as msgbox
    if msgbox.askyesno("退出程序", "确定要退出程序吗？"):
        # 停止定时器
        if update_timer:
            root.after_cancel(update_timer)
        
        # 先关闭所有子窗口（包括left.py窗口）
        for child in root.winfo_children():
            if isinstance(child, tk.Toplevel):
                try:
                    # 安全销毁子窗口
                    child.destroy()
                    # 等待窗口完全关闭
                    child.wait_visibility()
                except (tk.TclError, RuntimeError):
                    pass
        
        # 最后关闭主窗口
        try:
            root.quit()  # 先终止消息循环
            root.destroy()  # 再销毁窗口对象
        except tk.TclError:
            pass

root.protocol('WM_DELETE_WINDOW', on_closing)

# 设置窗口居中
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width - 800) // 2
y = (screen_height - 600) // 2
root.geometry(f"800x600+{x}+{y}")

# 设置背景颜色
root.configure(bg="#3E5C76")

# 标题标签
title_label = tk.Label(root, text="AI易经出行", font=("Helvetica", 36, "bold"), fg="yellow", bg="#3E5C76")
title_label.pack(pady=20)

# 说明文字标签
description_label = tk.Label(root, text="出行时了解方向运势吗?\n趋吉避凶-易经-概率学",
                             font=("Helvetica", 18), fg="yellow", bg="#3E5C76", wraplength=600)
description_label.pack(pady=10)

# 框架用于放置AI出行分析和出行日志按钮
button_frame = tk.Frame(root, bg="#3E5C76")
button_frame.pack(pady=20)

# AI出行分析按钮
# 修改open_analysis_window函数
def open_analysis_window():
    # 确保只打开一个实例
    if not hasattr(root, '_analysis_window') or not root._analysis_window.winfo_exists():
        try:
            from gui.left import AnalysisWindow
            root._analysis_window = AnalysisWindow(root)
            root._analysis_window.focus()
        except Exception as e:
            root.deiconify()
            import tkinter.messagebox as msgbox
            msgbox.showerror("错误", f"无法加载分析界面：{str(e)}")
            # 如果出错要恢复主窗口
            root.deiconify()

# 确保按钮命令正确绑定
ai_analysis_button = tk.Button(button_frame, text="AI出行分析", 
                              command=open_analysis_window,  # 确保使用函数引用
                              font=("Helvetica", 20), 
                              fg="yellow", bg="#2F657A",
                              width=15, height=2)
ai_analysis_button.pack(side=tk.LEFT, padx=10)

# 出行日志按钮
# 在顶部添加导入
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# 修改出行日志按钮的点击处理
def show_travel_log():
    # 创建统计窗口
    log_window = tk.Toplevel(root)
    log_window.title("出行日志统计")
    log_window.geometry("800x600")  # 修改整体宽度
    
    # 设置matplotlib中文字体
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    
    # 修改主容器边距设置（移除padx和pady参数）
    main_frame = tk.Frame(log_window, bg="#3E5C76")
    main_frame.pack(fill=tk.BOTH, expand=True)  # 移除 padx=50, pady=(0,50)
    
    # 添加标题
    title_frame = tk.Frame(main_frame, bg="#3E5C76", height=100)
    title_frame.pack(fill=tk.X)
    tk.Label(title_frame, text="出行日志统计", font=("SimHei", 24, "bold"), 
            fg="yellow", bg="#3E5C76").pack(pady=20)
    
    # 创建左右分割面板
    paned = tk.PanedWindow(main_frame, orient=tk.HORIZONTAL, bg="#3E5C76")
    paned.pack(fill=tk.BOTH, expand=True)
    
    # 左侧历史记录面板
    # 调整左侧面板宽度为320px（原420px）
    left_frame = tk.Frame(paned, bg="#3E5C76", width=320)  # 从420减少到320
    
    listbox = tk.Listbox(left_frame, 
                       font=("Helvetica", 12), 
                       width=20,  # 减少列数以适应新宽度
                       bg="#3E5C76",
                       fg="yellow")
    
    # 创建滚动条（补上缺失的滚动条定义）
    scrollbar = tk.Scrollbar(left_frame, bg="#3E5C76")
    listbox.config(yscrollcommand=scrollbar.set)  # 添加滚动条绑定
    scrollbar.config(command=listbox.yview)
    
    # 组装列表和滚动条
    listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    
    # 右侧图表面板 (290px)
    right_frame = tk.Frame(paned, bg="#3E5C76", width=290)
    
    # 组装分割面板时添加间隔
    paned.add(left_frame, minsize=320, stretch="never")  # 同步修改最小宽度
    paned.add(tk.Frame(paned, width=20, bg="#3E5C76"))
    paned.add(right_frame, minsize=290, stretch="never")
    
    # 调整图表尺寸
    fig = plt.Figure(figsize=(6,5), dpi=100)  # 缩小图表尺寸
    ax = fig.add_subplot(111)
    
    # 获取历史数据
    from infos.read_write_txt import UserInfo
    history = UserInfo.read_history()
    
    # 先定义方位列表
    directions = ['正东', '正南', '正西', '正北', '东南', '西南', '东北', '西北']  # 移至此位置
    
    # 填充左侧数据，获取listHistory.txt所有数据倒序显示
    # 循环中统计八方位的吉凶数量为后续图表显示左准备
    direction_counts = {d: {'吉': 0, '凶': 0} for d in directions}  # 现在可以正确引用directions
    
    for entry in reversed(history):
        parts = entry.split("→")
        if len(parts) >=3 and len(parts[1]) > 0 and len(parts[2]) > 0:
            # 插入列表数据
            listbox.insert(tk.END, f"{parts[0]} {parts[1]} {parts[2]}")
            
            # 统计吉凶数据
            direction = parts[1].strip().replace('方向', '')  # 去除可能存在的"方向"后缀
            result = parts[2].strip()[:1]  # 只取第一个字符
            
            # 严格校验方向合法性
            if direction in directions:
                # 规范结果字段
                if result.startswith('吉'):
                    direction_counts[direction]['吉'] += 1
                elif result.startswith('凶'):
                    direction_counts[direction]['凶'] += 1
                else:
                    print(f"无效结果字段: {parts[2]} → 条目: {entry}")
    print("统计数据：")
    print(direction_counts)
    # 创建统计图表
    fig = plt.Figure(figsize=(8,6), dpi=100)
    ax = fig.add_subplot(111)
    
    # 提取排序后的数据
    sorted_directions = sorted(directions)
    good = [direction_counts[d]['吉'] for d in sorted_directions]
    bad = [direction_counts[d]['凶'] for d in sorted_directions]
    
    # 绘制柱状图
    width = 0.35
    x = range(len(sorted_directions))  # 生成0-7的索引序列
    rects1 = ax.bar([i - width/2 for i in x], good, width, label='吉')  # 吉运柱左偏移
    rects2 = ax.bar([i + width/2 for i in x], bad, width, label='凶')   # 凶运柱右偏移
    
    # 添加数据标签（在图表上方补充以下代码）
    for rect in rects1 + rects2:
        height = rect.get_height()
        if height > 0:  # 只显示非零值
            ax.annotate(f'{height}',
                        xy=(rect.get_x() + rect.get_width() / 2, height),
                        xytext=(0, 3),  # 3 points vertical offset
                        textcoords="offset points",
                        ha='center', va='bottom')
    
    # 添加数据校验（在统计代码后补充）
    print("数据校验：")
    print("方位排序：", sorted_directions)
    print("吉运数据：", good)
    print("凶运数据：", bad)
    
    # 设置图表样式
    ax.set_xticks(x)
    ax.set_xticklabels(sorted_directions, fontproperties='SimHei')  # 使用排序后的标签
    ax.set_ylabel('次数', fontproperties='SimHei')  # 确保y轴标签使用中文
    ax.set_title("出行方向吉凶统计", fontsize=14)
    ax.set_xticks(x)
    ax.set_xticklabels(directions, fontproperties='SimHei')  # 设置坐标轴中文
    ax.legend()
    
    # 嵌入图表到Tkinter
    canvas = FigureCanvasTkAgg(fig, master=right_frame)
    canvas.draw()
    canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
    
    # 组装界面
    listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    listbox.config(yscrollcommand=scrollbar.set)
    scrollbar.config(command=listbox.yview)
    
    paned.add(left_frame)
    paned.add(right_frame)



# 查找并修改以下代码部分：

# 原按钮创建代码（约在56-61行）
travel_log_button = tk.Button(button_frame, text="出行日志", 
                             font=("Helvetica", 20), fg="yellow", bg="#2F657A",
                             width=15, height=2, command=show_travel_log)  # 直接绑定命令
travel_log_button.pack(side=tk.LEFT, padx=10)

# 修改出行日志按钮的command绑定
travel_log_button.config(command=show_travel_log)
# 框架用于放置姓名和出生日期输入区域
input_frame = tk.Frame(root, bg="#3E5C76")
input_frame.pack(pady=20)

def add_placeholder(entry, placeholder):
    entry.insert(0, placeholder)
    entry.config(fg="grey")
    def on_focus_in(_):
        if entry.get() == placeholder:
            entry.delete(0, tk.END)
            entry.config(fg="black")
    def on_focus_out(_):
        if not entry.get():
            entry.insert(0, placeholder)
            entry.config(fg="grey")
    entry.bind('<FocusIn>', on_focus_in)
    entry.bind('<FocusOut>', on_focus_out)

# 姓名标签和输入框
name_label = tk.Label(input_frame, text="姓名:", font=("Helvetica", 20), fg="yellow", bg="#3E5C76")
name_label.grid(row=0, column=0, padx=10, pady=10)
name_entry = tk.Entry(input_frame, font=("Helvetica", 20), width=20)
add_placeholder(name_entry, "请输入姓名")  # 添加placeholder提示
name_entry.grid(row=0, column=1, padx=10, pady=10)

# 出生日期标签和输入框
date_label = tk.Label(input_frame, text="出生日期:", font=("Helvetica", 20), fg="yellow", bg="#3E5C76")
date_label.grid(row=1, column=0, padx=10, pady=10)
date_entry = tk.Entry(input_frame, font=("Helvetica", 20), width=20)
add_placeholder(date_entry, "例如：1990年01月01日")  # 添加日期格式提示
date_entry.grid(row=1, column=1, padx=10, pady=10)

# 读取和存储按钮框架
button_frame_2 = tk.Frame(root, bg="#3E5C76")
button_frame_2.pack(pady=10)  # 减少垂直间距

# 读取按钮
def load_user_info():
    from infos.read_write_txt import UserInfo
    user_data = UserInfo.read_user_info()
    if user_data:
        # 清除原有内容并填入新数据
        name_entry.delete(0, tk.END)
        name_entry.insert(0, user_data[0])
        name_entry.config(fg="black")  # 确保文字颜色正确
        
        date_entry.delete(0, tk.END)
        date_entry.insert(0, user_data[1])
        date_entry.config(fg="black")

read_button = tk.Button(button_frame_2, text="读取", font=("Helvetica", 20), fg="yellow", bg="#3E5C76",
                        width=10, height=1, command=load_user_info)  # 添加命令绑定
read_button.pack(side=tk.LEFT, padx=10)

# 存储按钮
def save_user_info():
    import tkinter.messagebox as msgbox
    # 获取输入内容（过滤空格）
    name = name_entry.get().strip()
    birthday = date_entry.get().strip()
    
    # 验证输入完整性
    if not name or name == "请输入姓名":
        msgbox.showwarning("输入不完整", "请输入姓名")
        name_entry.focus()
        return
        
    if not birthday or birthday == "例如：1990年01月01日":
        msgbox.showwarning("输入不完整", "请输入出生日期")
        date_entry.focus()
        return
    
    # 调用存储功能
    from infos.read_write_txt import UserInfo
    try:
        UserInfo.write_user_info(name, birthday)
        msgbox.showinfo("操作成功", "用户信息保存成功")
    except Exception as e:
        msgbox.showerror("保存失败", f"发生错误：{str(e)}")

save_button = tk.Button(button_frame_2, text="存储", font=("Helvetica", 20), fg="yellow", bg="#3E5C76",
                        width=10, height=1, command=save_user_info)  # 添加命令绑定
save_button.pack(side=tk.LEFT, padx=10)

# 当前系统日期标签
# 在全局区域添加线程锁
click_lock = threading.Lock()

# 修改点击处理函数
def show_mysql_info(event):
    def async_task():
        if click_lock.acquire(blocking=False):
            try:
                # 禁用点击效果并更新光标
                root.after(0, lambda: event.widget.config(cursor="watch"))
                
                # 在主线程创建弹窗
                root.after(0, create_popup_window)
                
                # 获取数据
                from db.mysql_db import MySQLDB
                data = MySQLDB.get_mysql_msg()
                
                # 更新弹窗内容
                root.after(0, lambda: update_popup_content(data))
                
            except Exception as e:
                root.after(0, lambda: update_popup_content(f"获取数据失败：{str(e)}"))
            finally:
                root.after(0, lambda: event.widget.config(cursor="hand2"))
                click_lock.release()
        else:
            root.after(0, lambda: update_popup_content("请等待当前请求完成..."))
            return

    threading.Thread(target=async_task, daemon=True).start()

def create_popup_window():
    global popup, text_area
    popup = tk.Toplevel(root)
    popup.title("详细时辰信息")
    popup.geometry("1000x800+100+100")
    popup.configure(bg="#3E5C76")
    
    # 添加滚动条
    scrollbar = tk.Scrollbar(popup)
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

    # 创建文本显示区域
    text_area = tk.Text(popup, wrap=tk.WORD, yscrollcommand=scrollbar.set,
                       bg="#3E5C76", fg="yellow", font=("Helvetica", 12), padx=20, pady=20)
    text_area.pack(expand=True, fill=tk.BOTH)
    text_area.insert(tk.END, "黄历数据加载中，请稍等...")
    text_area.config(state=tk.DISABLED)
    
    scrollbar.config(command=text_area.yview)

def update_popup_content(data):
    text_area.config(state=tk.NORMAL)
    text_area.delete(1.0, tk.END)
    if isinstance(data, str) and data.startswith("获取数据失败"):
        text_area.insert(tk.END, data)
    else:
        formatted_data = data.replace(",", "\n\n")
        text_area.insert(tk.END, formatted_data)
    text_area.config(state=tk.DISABLED)

# 当前系统日期标签（添加点击绑定）
date_info_label = tk.Label(root, text="当前系统日期: 正在获取时间...",
                          font=("Helvetica", 20), fg="yellow", bg="#3E5C76",
                          cursor="hand2")  # 添加手型光标
date_info_label.pack(pady=10)
date_info_label.bind("<Button-1>", show_mysql_info)  # 绑定点击事件

# 添加时间更新功能
# 在全局区域添加
update_timer = None

def update_time():
    global update_timer
    import time
    current_time = time.strftime("%Y年%m月%d日%H:%M:%S")
    date_info_label.config(text=f"当前系统日期: {current_time}")
    update_timer = root.after(1000, update_time)

# 启动时间更新
update_time()

root.mainloop()